package com.jifeng.br.pjj.bookreader.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jifeng.br.pjj.bookreader.entity.RecordEntity;
import com.jifeng.br.pjj.bookreader.mapper.RecordMapper;
import com.jifeng.br.pjj.bookreader.service.RecordService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @Author PangJunjie
 * @Date 2023/7/19/019
 */
@Service
@Transactional
public class RecordServiceImpl extends ServiceImpl<RecordMapper, RecordEntity> implements RecordService {
    @Override
    public IPage<RecordEntity> getPage(int page, int limit, RecordEntity record) {
        return this.page(new Page<>(page, limit), new QueryWrapper<RecordEntity>()
                .eq("user_id", record.getUserId())
                .orderByDesc("read_time")
        );
    }

    @Override
    public void saveRecord(RecordEntity record) {
        RecordEntity recordEntity = this.getOne(new QueryWrapper<RecordEntity>().eq("user_id", record.getUserId()).eq("book_id", record.getBookId()));
        if (recordEntity == null) {
            this.save(record);
        } else {
            recordEntity.setCatalogId(record.getCatalogId());
            recordEntity.setReadTime(new Date());
            this.updateById(recordEntity);
        }
    }

    @Override
    public void deleteRecord(int bookId) {
        this.remove(new QueryWrapper<RecordEntity>().eq("book_id", bookId));
    }
}
